package com.bole.service.impl;

import com.bole.dao.AdminDao;
import com.bole.dao.AdminRoleDao;
import com.bole.data.Result;
import com.bole.pojo.AdminRoleDo;
import com.bole.pojo.TbAdminDo;
import com.bole.service.AdminService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yakamaxi
 * @version 1.0
 * @date 2020/8/12 13:30
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminDao adminDao;
    @Resource
    private AdminRoleDao adminRoleDao;

    @Override
    public List<TbAdminDo> getInfo() {
        return adminDao.findAll();
    }

    @Override
    public void add(TbAdminDo adminDo, Long rid) {
        // 默认密码 1234
        adminDo.setSalt("ba93");
        adminDo.setPassword("428e9b21870f84a958fea4904625852e");
        adminDao.save(adminDo);
        AdminRoleDo adminRoleDo = new AdminRoleDo();
        adminRoleDo.setAdminId(adminDo.getId());
        adminRoleDo.setRoleId(rid);
        // 中间表保存
        adminRoleDao.save(adminRoleDo);
//        Long id = adminDo.getId();
//        List<AdminRoleDo> list = new ArrayList<>();
//        Arrays.stream(rids).forEach(adminRoleDo::setRoleId);
//        for (Long rid : rids) {
        // 获取用户的主键id

        // 将rid设置到该对象中

//            list.add(adminRoleDo);
//        }
        // 增加中间表(用户和角色进行关联) 用户的主键id 和 角色的主键id
//        adminRoleDao.saveAll(list);
    }

    @Override
    public TbAdminDo getAdminById(Long id) {

        return adminDao.findTbAdminDoById(id);
    }

    @Override
    public void updateById(TbAdminDo admin, Long rid) {
        TbAdminDo tbAdminDoById = adminDao.findTbAdminDoById(admin.getId());
        tbAdminDoById.setUsername(admin.getUsername());
        adminDao.save(tbAdminDoById);
        // 先查再删
//        Long admin_RoleId = adminRoleDao.findRoleByAdminId(admin.getId());
        AdminRoleDo byAdminId = adminRoleDao.findByAdminId(admin.getId());
        // 删除中间表数据
        adminRoleDao.delete(byAdminId);
//        List<AdminRoleDo> adminRoleDos = new ArrayList<>();
//        Arrays.stream(rids).forEach(adminRoleDo::setRoleId);
//        for (Long rid : rids) {
        AdminRoleDo adminRoleDo = new AdminRoleDo();
        // 获取用户的主键id
        adminRoleDo.setAdminId(admin.getId());
        // 将rid设置到该对象中
        adminRoleDo.setRoleId(rid);
//            adminRoleDos.add(adminRoleDo);
//        }
        // 增加中间表(用户和角色进行关联) 用户的主键id 和 角色的主键id
        adminRoleDao.save(adminRoleDo);
        // redis ????
    }

    @Override
    public void deleteById(Long id) {
        // 删除用户信息
        adminDao.deleteById(id);
        // 删除中间表信息, 还是先查再删
        AdminRoleDo byAdminId = adminRoleDao.findByAdminId(id);
        adminRoleDao.delete(byAdminId);
    }

    // 可能用于登录验证的查询
    @Override
    public TbAdminDo getInfoByName(String username) {
        return adminDao.findTbAdminDoByName(username);
    }
}
